package com.hongyi.controller;

import com.hongyi.utils.http.HttpUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: hongyi
 * @CreateTime: 2024-10-22
 */


public class HttpUtilsDemo {
    public static void main(String[] args) {
        String host = "https://jsonplaceholder.typicode.com";
        String path = "/posts/1";
        String method = "GET";

        // 构造空的headers和querys，因为该接口不需要它们
        Map<String, String> headers = new HashMap<>();
        Map<String, String> querys = new HashMap<>();

        try {
            // 调用doGet方法
            HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);

            // 检查响应状态码，这里简单判断是否为200 OK
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                // 获取响应体
                HttpEntity entity = response.getEntity();
                // 将响应体内容转换为字符串
                String jsonResponse = EntityUtils.toString(entity, "UTF-8");
                // 打印或处理返回的JSON字符串
                System.out.println(jsonResponse);
            } else {
                // 处理非200状态码的情况
                System.out.println("Failed to retrieve data: HTTP status code " + statusCode);
            }
        } catch (Exception e) {
            // 处理异常，例如网络错误、SSL问题等
            e.printStackTrace();
        }
    }
}
